import React from 'react';
import {
  Dimensions,
  Image,
  StyleSheet,
  Text,
  View,
} from 'react-native';


export default class ProjectGrid extends React.Component {
  static defaultProps = {
    data: [],
    hasLine: true,
    itemStyle: {},
    columnNum: 3
  };

  getFlexItemStyle() {
    return {
      height: Dimensions.get('window').width / 4,
      borderRightWidth: this.props.hasLine ? 1 : 0,
    };
  }

  render() {
    const {
      data,
      hasLine,
      onClick = () => {
      },
    } = this.props;
    // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11640
    const columnNum = data.length <= 2?data.length:3;

    const customItemStyle = this.props.itemStyle;
    const dataLength = (data && data.length) || 0;
    // const rowCount = Math.ceil(dataLength / columnNum);
    const rowCount = 1;
    const renderItem =
      this.props.renderItem ||
      ((dataItem, index) => (
        <View
          style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}
          onPress={() => onClick(dataItem, index)}
        >
          {React.isValidElement(dataItem.icon) ? (
            dataItem.icon
          ) : (
            <Image source={{uri: dataItem.icon}} style={styles.icon}/>
          )}
          <Text style={styles.text}>{dataItem.text}</Text>
        </View>
      ));

    const flexItemStyle = this.getFlexItemStyle();
    const rowsArr = [];


    for (let i = 0; i < rowCount; i++) {
      const rowArr = [];
      for (let j = 0; j < columnNum; j++) {
        const dataIndex = i * columnNum + j;
        if (dataIndex < dataLength) {
          const el = data && data[dataIndex];
          rowArr.push(
            <View
              key={j}
              style={[
                styles.grayBorderBox,
                flexItemStyle,
                {flex: 1, borderLeftWidth: hasLine && j === 0 ? 1 : 0},
                customItemStyle,
              ]}
              onPress={() => onClick(el, dataIndex)}
            >
              {renderItem(el, dataIndex)}
            </View>,
          );
        } else {
          rowArr.push(
            <View key={j} style={[styles.grayBorderBox, flexItemStyle, {flex: 1}]}/>,
          );
        }
      }
      const boxBorderStyle = {
        borderTopWidth: hasLine && i === 0 ? 1 : 0,
        borderBottomWidth: hasLine ? 1 : 0,
      };
      rowsArr.push(
        <View key={i} style={[styles.grayBorderBox, boxBorderStyle, {flexDirection: 'row'}]}>
          {rowArr}
        </View>,
      );
    }
    console.log('rowsArr', rowsArr)
    return (
      <View>{rowsArr}</View>
    );
  }
}

const styles = StyleSheet.create({
  grayBorderBox: {
    borderColor: '#dddddd',
  },
  icon: {
    width: 22,
    height: 22,
  },
  text: {
    fontSize: 12,
    color: '#000000',
    marginTop: 4,
  },
})
